<?php

namespace app\home\controller;

use app\common\model\Cate as CateModel;
use app\common\model\Article as ArticleModel;
use think\Db;

class Cate extends HomeCommon
{
    public function index($id = null,$key_word = null)
    {
        $cateModel = new CateModel();
        $top_cate_id = 0;
        $where = [];
        if ($id) {
            $current_cate = $cateModel->get($id);
            if ($current_cate->pid == 0) {
                $top_cate_id = $id;
            } else {
                $top_cate_id = $current_cate->pid;
            }
            $children = $cateModel->query(sprintf('select group_concat(id) as str from %s where pid=%d',$cateModel->getTable(),$id));
            if($children && $children[0]['str']){
                $str = $children[0]['str'].','.$id;
                $where['cate_id'] = ['in',[$str]];
            }else{
                $where['cate_id'] = $id;
            }
        }
        if($key_word){
            $where['title'] = ['like',"%{$key_word}%"];
        }
        $articleModel = new ArticleModel();
        $this->assign('article_list',$articleModel->where($where)->order(['article_sort'=>'desc'])->paginate(12));
        $this->assign('top_cate_id',$top_cate_id);
        $this->assign('cate_list',$cateModel->getHomeCateList());
        return $this->fetch();
    }
}